package cn.ljy.authority.service.impl;


import cn.ljy.authority.config.SysWecharConfig;
import cn.ljy.authority.dao.mapper.SysUserMapper;
import cn.ljy.authority.dao.mapper.SysWechatUserMapper;
import cn.ljy.authority.model.SysWechatUser;
import cn.ljy.authority.model.query.SysWechatUserQuery;
import cn.ljy.authority.service.SysWechatUserService;
import cn.ljy.authority.utils.JwtUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Validated
@Service
public class ISysWechatUserServiceImpl extends IBaseService<SysWechatUser, SysWechatUserQuery> implements SysWechatUserService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SysWecharConfig wechatConfig;

    @Autowired
    private SysWechatUserMapper wechatUserMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private JwtUtils jwtUtils;

    private final ObjectMapper objectMapper = new ObjectMapper();

   /* @Override
    public WechatSessionResponse getWechatSession(String code) {
        try {
            String url = wechatConfig.getSessionUrl(code);
            WechatSessionResponse response = restTemplate.getForObject(url, WechatSessionResponse.class);

            if (response == null) {
                throw new BusinessException("微信服务调用失败");
            }

            if (!response.isSuccess()) {
                log.error("微信登录失败: {} - {}", response.getErrcode(), response.getErrmsg());
                throw new BusinessException("微信登录失败: " + response.getErrmsg());
            }

            return response;
        } catch (Exception e) {
            log.error("获取微信session失败: ", e);
            throw new BusinessException("微信服务异常");
        }
    }*/

//    @Override
//    @Transactional
//    public SysUser loginOrRegisterByWechat(String code) {
//        WechatSessionResponse session = getWechatSession(code);
//        String openId = session.getOpenid();
//
//        // 查找已绑定的微信用户
//        SysWechatUser wechatUser = wechatUserMapper.selectByOpenId(openId);
//
//        if (wechatUser != null) {
//            // 更新sessionKey
//            wechatUser.setSessionKey(session.getSession_key());
//            wechatUser.setUpdateTime(new Date());
//            wechatUserMapper.update(wechatUser);
//
//            // 返回对应的系统用户
//            SysUser sysUser = userMapper.selectById(wechatUser.getUserId());
//            if (sysUser == null) {
//                throw new BusinessException("绑定的系统用户不存在");
//            }
//            return sysUser;
//        }
//
//        // 微信用户未绑定，创建新用户
//        return createUserByWechat(session);
//    }

   /* private SysUser createUserByWechat(WechatSessionResponse session) {
        // 创建系统用户
        SysUser user = new SysUser();
        user.setUsername("wx_" + System.currentTimeMillis());
        user.setNickName("微信用户");
        user.setSex(0);
        user.setStatus(1);
        user.setDeleteStatus(false);
        user.setCreateTime(new Date());

        userMapper.insert(user);

        // 创建微信用户关联
        SysWechatUser wechatUser = new SysWechatUser();
        wechatUser.setUserId(user.getId());
        wechatUser.setOpenId(session.getOpenid());
        wechatUser.setSessionKey(session.getSession_key());
        wechatUser.setUnionId(session.getUnionid());
        wechatUser.setCreateTime(new Date());

        wechatUserMapper.insert(wechatUser);

        return user;
    }*/

   /* @Override
    public SysWechatUser getWechatUserByOpenId(String openId) {
        return wechatUserMapper.selectByOpenId(openId);
    }

    @Override
    public SysWechatUser getWechatUserByUserId(Long userId) {
        return wechatUserMapper.selectByUserId(userId);
    }*/

   /* @Override
    @Transactional
    public boolean bindWechatUser(Long userId, String openId, String sessionKey) {
        try {
            // 检查用户是否存在
            SysUser user = userMapper.selectById(userId);
            if (user == null) {
                throw new BusinessException("用户不存在");
            }

            // 检查微信用户是否已被绑定
            SysWechatUser existing = wechatUserMapper.selectByOpenId(openId);
            if (existing != null) {
                throw new BusinessException("该微信账号已被绑定");
            }

            // 创建绑定关系
            SysWechatUser wechatUser = new SysWechatUser();
            wechatUser.setUserId(userId);
            wechatUser.setOpenId(openId);
            wechatUser.setSessionKey(sessionKey);
            wechatUser.setCreateTime(new Date());

            return wechatUserMapper.insert(wechatUser) > 0;
        } catch (Exception e) {
            log.error("绑定微信用户失败: ", e);
            throw new BusinessException("绑定失败");
        }
    }*/

   /* @Override
    public boolean unbindWechatUser(Long userId) {
        return wechatUserMapper.deleteByUserId(userId) > 0;
    }

    @Override
    public boolean updateWechatUserInfo(SysWechatUser wechatUser) {
        wechatUser.setUpdateTime(new Date());
        return wechatUserMapper.update(wechatUser) > 0;
    }

    @Override
    public String decryptData(String encryptedData, String sessionKey, String iv) {
        // 这里需要实现微信数据解密逻辑
        // 由于涉及加密算法，这里只提供方法框架
        try {
            // 实现AES解密逻辑
            // 返回解密后的JSON字符串
            return "{\"nickName\":\"微信用户\",\"avatarUrl\":\"\"}";
        } catch (Exception e) {
            log.error("数据解密失败: ", e);
            throw new BusinessException("数据解密失败");
        }
    }*/
}